package org.unt.logic;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.unt.genlogic.Files;

public class Subtitles {

	public static void main(String[] args) throws IOException, ParseException {

		// Files.info();
		// if (true) return;

		init();

		int from = 426;

		List<String> lines1 = Files.readFileAsList(new File("d:/babel 2 - 1.srt"), "windows-1252");
		List<String> lines2 = Files.readFileAsList(new File("d:/babel 2 - 2.srt"), "windows-1252");

		for (int i = 0; i < lines2.size(); i++) {

			if (lines2.get(i) == null || "".equals(lines2.get(i))) {
				lines1.add(lines2.get(i));
			} else if (isInteger(lines2.get(i))) {
				lines1.add("" + (from + Integer.parseInt(lines2.get(i))));
			} else if (isInteger(lines2.get(i).substring(0, 1))) {
				lines1.add(add1(lines2.get(i)));
			} else {
				lines1.add(lines2.get(i));
			}
		}

		Files.writeToFile(lines1, "d:/babel 2.srt", "windows-1252"); // UTF-8 windows-1252 ISO-8859-1
	}

	static String add1(String line) throws ParseException {
		String[] str = line.split(" --> ");
		return add2(str[0]) + " --> " + add2(str[1]);
	}

	static String base = "01 01 2000 ";
	static SimpleDateFormat dateFormatter1 = new SimpleDateFormat("dd MM yyyy hh:mm:ss,SSS");
	static SimpleDateFormat dateFormatter2 = new SimpleDateFormat("hh:mm:ss,SSS");
	static Date date0;
	static Date date1;

	static void init() throws ParseException {
		date0 = dateFormatter1.parse(base + "00:00:00,000");
		date1 = dateFormatter1.parse(base + "01:05:47,273");
	}

	static String add2(String time) throws ParseException {
		Date date2 = dateFormatter1.parse(base + time);
		Date date3 = new Date(date1.getTime() + (date2.getTime() - date0.getTime()));
		return dateFormatter2.format(date3);
	}

	static boolean isInteger(String str) {
		try {
			Integer.parseInt(str);
		} catch (NumberFormatException e) {
			return false;
		}
		return true;
	}
}
